# 学生信息管理系统
import os

student_path = 'student.txt'


def main():
    while True:
        menu()
        choose = int(input('请选择：'))
        if choose in [0, 1, 2, 3, 4, 5, 6, 7]:
            if choose == 0:
                answer = input('你确定要退出系统？Y/N')
                if answer == 'Y' or answer == 'y':
                    print('谢谢你的使用！')
                    break  # 结束程序
                else:
                    continue  # 跳过当前循环
            if choose == 1:
                insert()
            if choose == 2:
                search()
            if choose == 3:
                delete()
            if choose == 4:
                modify()
            if choose == 5:
                sort()
            if choose == 6:
                total()
            if choose == 7:
                show()


def menu():
    '''菜单函数'''
    print("===============================学生信息管理系统===============================")
    print('----------------------------------功能菜单-----------------------------------')
    print('        1.录入学生信息；')
    print('        2.查找学生信息；')
    print('        3.删除学生信息；')
    print('        4.修改学生信息；')
    print('        5.排序；')
    print('        6.统计学生人数；')
    print('        7.显示所有学生信息；')
    print('        0.退出系统；')
    print('---------------------------------------------------------------------------')


def insert():
    student_list = []
    while True:
        id = input('请输入学生ID:')
        if not id:
            break
        name = input('请输入学生姓名:')
        if not name:
            break
        try:
            chinese = int(input('请输入语文成绩：'))
            maths = int(input('请输入数学成绩：'))
            english = int(input('请输入英语成绩：'))
        except:
            print('无效参数，请重新输入数值！')
            continue
        # 录入数据都没有问题，保存数据
        student_info = {'id': id, 'name': name, 'chinese': chinese, 'maths': maths, 'english': english}
        student_list.append(student_info)
        anwser = input('是否继续录入？Y/N')
        if anwser == 'Y' or anwser == 'y':
            continue
        else:
            break

    # 保存录入学生信息
    save(student_list)
    print('录入学生信息完毕！')


def save(lst):
    try:
        student_file = open(student_path, 'a', encoding='UTF-8')
    except:
        student_file = open(student_path, 'w', encoding='UTF-8')
    for item in lst:
        student_file.write(str(item) + '\n')
    student_file.close()


student_query = []
def search():
    if os.path.exists(student_path):
        with open(student_path, 'r', encoding='UTF-8') as rfile:
            student_list = rfile.readlines()
    else:
        print('暂无内容！')
        return
    student_id = input('请输入学生ID：')
    if not student_id:
        print('学生ID为空，请重新输入：')
        search();
    for item in student_list:
        d = dict(eval(item))
        if d['id'] == student_id:
            student_query.append(item)
            break
    if not student_query:
        print('暂未查询到学生信息！')
    answer = input('是否继续查询学生信息；Y/N')
    if answer == 'Y' or answer =='y':
        search()
    else:
        print('查询结果信息为：\n')
        #字符串格式输出
        title = '{:^6}\t{:^12}\t{:^8}\t{:^8}\t{:^8}'
        print(title.format('ID', '姓名', '语文', '英语', '数学'))
        data_format = '{:^6}\t{:^12}\t{:^8}\t{:^8}\t{:^8}'
        for item in student_query:
            #print(item)
            d = dict(eval(item))
            print(data_format.format(d['id'], d.get('name'), d['chinese'], d['maths'], d['english']))


def delete():
    while True:
        student_id = input('请输入要删除学生的ID：')
        if student_id:
            if os.path.exists(student_path):
                with open(student_path, 'r', encoding='UTF-8') as rfile:
                    student_old_list = rfile.readlines()
            else:
                student_old_list = []
            # 定义是否删除学生信息标记Flase无， True有
            flag = False
            if student_old_list:
                with open(student_path, 'w', encoding='UTF-8') as wfile:
                    d = {}
                    for item in student_old_list:
                        d = dict(eval(item))
                        if d['id'] != student_id:
                            wfile.write(str(item) + '\n')
                        else:
                            flag = True
                    if flag:
                        print(f'学生ID：{student_id}的信息已被删除')
                    else:
                        print(f'没找的学生ID：{student_id}的信息')
            else:
                print('暂无学生信息！')
                break
            #展示学生信息
            show()
            answer = input('是否继续删除学生信息;Y/N')
            if answer=='Y' or answer=='y':
                continue
            else:
                break


def modify():
    #查看所有的学生信息
    show()
    if os.path.exists(student_path):
        with open(student_path, 'r', encoding='UTF-8') as rfile:
            student_old_list = rfile.readlines()
    else:
        return
    student_id = input('请输入学生ID：')
    with open(student_path, 'w', encoding='UTF-8') as wfile:
        for item in student_old_list:
            d = dict(eval(item))
            if d['id'] == student_id:
                print('找到学生的相关信息，可以进行修改：')
                while True:
                    try:
                        d['name'] = input('请输入学生姓名:')
                        d['chinese'] = int(input('请输入语文成绩：'))
                        d['maths'] = int(input('请输入数学成绩：'))
                        d['english'] = int(input('请输入英语成绩：'))
                    except:
                        print('无效参数，请重新输入数值！')
                    else:
                        #try...except..else 没有出现异常执行此代码；
                        break
                wfile.write(str(d)+'\n')
                print('修改成功！')
            else:
                wfile.write(str(d)+'\n')
        answer = input('是否继续修改；Y/N')
        if answer =='Y' or answer =='y':
            modify()
        else:
            print('修改结束。。。')


def sort():
    now_list = []
    if not os.path.exists(student_path):
        print('暂无数据。')
    with open(student_path, 'r', encoding='UTF-8') as rfile:
        student_list = rfile.readlines()
    if not student_list:
        print('暂无数据。')
    for item in student_list:
        d = dict(eval(item))
        now_list.append(d)
    sort_num = int(input('请输入排序规则，1：升序；2：降序'))
    print(sort_num, type(sort_num))
    if sort_num == 1:
        sort_flag = False
    elif sort_num == 2:
        sort_flag = True
    else:
        print('排序规则有误！请重新输入')
        sort()

    sort_type = int(input('请输入排序字段：1：语文；2：英语；3：数学'))
    if sort_type == 1:
        now_list.sort(key=lambda x: int(x['chinese']), reverse=sort_flag)
    elif sort_type == 2:
        now_list.sort(key=lambda x: int(x['english']), reverse=sort_flag)
    elif sort_type == 3:
        now_list.sort(key=lambda x: int(x['maths']), reverse=sort_flag)
    #展示学生信息
    # 格式化展示学生信息列表格式
    title = '{:^6}\t{:^12}\t{:^8}\t{:^8}\t{:^8}'
    print(title.format('ID', '姓名', '语文', '英语', '数学'))
    data_format = '{:^6}\t{:^12}\t{:^8}\t{:^8}\t{:^8}'
    for d in now_list:
        print(data_format.format(d['id'], d.get('name'), d['chinese'], d['maths'], d['english']))
    print('展示数据结束。')


def total():
    if not os.path.exists(student_path):
        print('暂无信息')
        return
    with open(student_path, 'r', encoding='UTF-8') as rfile:
        student_list = rfile.readlines()
    if not student_list:
        print('暂无信息')
        return
    print('当前学生信息共有：',len(student_list))

def show():
    if not os.path.exists(student_path):
        print('暂无数据！')
        return
    with open(student_path, 'r', encoding='UTF-8') as rfile:
        student_list = rfile.readlines()
    if not student_list:
        print('暂无数据')
        return
    show_format(student_list)


def show_format(lst):
    '''展示学生信息列表数据'''
    # 格式化展示学生信息列表格式
    title = '{:^6}\t{:^12}\t{:^8}\t{:^8}\t{:^8}'
    print(title.format('ID', '姓名', '语文', '英语', '数学'))
    data_format = '{:^6}\t{:^12}\t{:^8}\t{:^8}\t{:^8}'
    for item in lst:
        d = dict(eval(item))
        print(data_format.format(d['id'], d.get('name'), d['chinese'], d['maths'], d['english']))
    print('展示数据结束。')


if __name__ == '__main__':
    main()
